package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.entity.vo.MemberLoginVo;
import com.atguigu.gulimall.member.entity.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.entity.vo.SocialUser;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.service.MemberLevelService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAcct = vo.getLoginAcct();
        String password = vo.getPassword();

        //1、去数据库查询
        LambdaQueryWrapper<MemberEntity> queryWrapper = new LambdaQueryWrapper<>();
        MemberEntity entity = this.baseMapper.selectOne(queryWrapper.eq(MemberEntity::getUsername, loginAcct).or().eq(MemberEntity::getMobile, loginAcct));
        if (entity == null) {
            //登录失败（账号不存在）
            return null;
        } else {
            //存在此账号，开始验证密码
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行密码匹配
            if (passwordEncoder.matches(password, passwordDb)) {
                //登录成功
                return entity;
            } else {
                //密码错误
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        String uid = socialUser.getUid();
        //1.判断当前社交用户是否登录过系统
        LambdaQueryWrapper<MemberEntity> queryWrapper = new LambdaQueryWrapper<>();
        MemberEntity memberEntity = this.baseMapper.selectOne(queryWrapper.eq(MemberEntity::getSocialUid, uid));
        if (memberEntity != null) {
            //这个用户已经注册
            MemberEntity loginEntity = new MemberEntity();
            loginEntity.setId(memberEntity.getId());
            loginEntity.setAccessToken(socialUser.getAccessToken());
            loginEntity.setExpiresIn(socialUser.getExpiresIn());

            this.baseMapper.updateById(loginEntity);

            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpiresIn(socialUser.getExpiresIn());
            return memberEntity;
        } else {
            //该用户没有注册（第一次登录）
            MemberEntity registerEntity = new MemberEntity();

            try {
                //查询当前社交账号的基本信息
                Map<String, String> map = new HashMap<>();
                map.put("access_token", socialUser.getAccessToken());
                map.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), map);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);

                    //获取社交账号的信息并赋值给新账号
                    registerEntity.setNickname(jsonObject.getString("name"));   //昵称
                    registerEntity.setGender("m".equalsIgnoreCase(jsonObject.getString("gender")) ? 1 : 0); //性别
                    //......
                }
            } catch (Exception e) { }

            registerEntity.setSocialUid(socialUser.getUid());
            registerEntity.setAccessToken(socialUser.getAccessToken());
            registerEntity.setExpiresIn(socialUser.getExpiresIn());

            this.baseMapper.insert(registerEntity);

            return registerEntity;

        }
    }

    @Override
    public boolean register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();

        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelService.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否唯一
        checkMemberUnique(vo);

        //设置手机和用户名
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUsername());

        //密码加密存储（盐值MD5）
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        entity.setNickname(vo.getUsername());

        //TODO 其他需要保存的会员用户默认信息

        //保存
        this.baseMapper.insert(entity);
        return true;
    }

    /**
     * 检查需要注册的用户信息的唯一性（不可被注册时抛出异常）
     *
     * @author 胡菜鸡
     * @date 2022/1/14 11:38
     */
    private void checkMemberUnique(MemberRegisterVo vo) {
        LambdaQueryWrapper<MemberEntity> queryWrapper = new LambdaQueryWrapper<>();

        Integer phone = this.baseMapper.selectCount(queryWrapper.eq(MemberEntity::getMobile, vo.getPhone()));
        if (phone > 0) {
            throw new PhoneExistException();
        }

        Integer username = this.baseMapper.selectCount(queryWrapper.eq(MemberEntity::getUsername, vo.getUsername()));
        if (username > 0) {
            throw new UsernameExistException();
        }
    }

}